package lion.netty4.message;

import java.io.IOException;

import com.google.protobuf.CodedOutputStream;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.util.ReferenceCountUtil;

public class MySendToMessage {

	private CodedOutputStream codedOutputStream;

	private ByteBuf buffer;

	private int msgCode = 0;
	
	private boolean formated = false;

	public MySendToMessage(ByteBufAllocator alloc, int pMsgCode) throws IOException {
		buffer = alloc.buffer(32);
		codedOutputStream = CodedOutputStream.newInstance(new ByteBufOutputStream(buffer), 32);
		//
		codedOutputStream.writeInt32NoTag(pMsgCode);
		this.msgCode = pMsgCode;
	}
	
	public ByteBuf entireMsg() throws IOException{
		codedOutputStream.flush();
		return buffer;
	}

	public ByteBuf entireMsgAll() throws IOException {
		if (!formated) {
			codedOutputStream.flush();
			formated = true;
		}
		return buffer.copy();
	}

	public MySendToMessage writeBool(boolean b) throws IOException {
		codedOutputStream.writeBoolNoTag(b);
		return this;
	}

	public MySendToMessage writeInt(int i) throws IOException {
		codedOutputStream.writeInt32NoTag(i);
		return this;
	}

	public MySendToMessage writeLong(long i) throws IOException {
		codedOutputStream.writeInt64NoTag(i);
		return this;
	}

	public MySendToMessage writeByte(byte i) throws IOException {
		codedOutputStream.writeRawByte(i);
		return this;
	}

	public MySendToMessage writeFloat(float val) throws IOException {
		codedOutputStream.writeFloatNoTag(val);
		return this;
	}

	public int getMsgCode() {
		return msgCode;
	}

	public void setMsgCode(int msgCode) {
		this.msgCode = msgCode;
	}

	public MySendToMessage writeString(String str) throws IOException {
		if(str == null){
			str = "";
		}
		codedOutputStream.writeStringNoTag(str);
		return this;
	}

	public MySendToMessage writeBytes(byte[] bytes) throws IOException {
		codedOutputStream.writeRawBytes(bytes);
		return this;
	}

	public void release() {
		ReferenceCountUtil.release(buffer);		
	}

}
